<template>
  <section class="padding">
    <el-card class="box-card">
      <el-row v-if="waybillBtn" class="waybill-nav">
        <el-col
          v-for="(item, index) in waybillBtn"
          :key="index"
          :span="3"
          class="waybill-nav-item"
          @click.native="getWaybill(item.status)"
        >
          <div
            class="pan-btn green-btn "
            :class="{ 'btn-active': item.status === status }"
          >
            {{ $t(`waybill.${item.name}`) + `(${item.number})` }}
          </div>
        </el-col>
      </el-row>
      <el-form
        :inline="true"
        :model="searchCriteria"
        class="margin-top-sm padding-top "
        size="mini"
        label-width="70px"
      >
        <el-row>
          <el-col :span="20">
            <el-row>
              <el-col :span="5">
                <el-form-item label="渠道">
                  <el-select
                    v-model="searchCriteria.inStockChannel"
                    filterable
                    placeholder="渠道"
                  >
                    <el-option
                      v-for="(item, val) in publicData.channelMap"
                      :key="val"
                      :label="item"
                      :value="val"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="目的国家">
                  <el-select
                    v-model="searchCriteria.countryId"
                    filterable
                    placeholder="目的国家"
                  >
                    <el-option
                      v-for="item in publicData.countryList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="5">
                <el-form-item label="运单号">
                  <el-input
                    v-model.trim="searchCriteria.waybillNo"
                    placeholder="运单号"
                  />
                </el-form-item>
                <el-form-item label="SKU">
                  <el-input
                    v-model.trim="searchCriteria.sku"
                    placeholder="SKU"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="追踪号">
                  <el-input
                    v-model.trim="searchCriteria.trackNumber"
                    placeholder="追踪号"
                  />
                </el-form-item>
                <el-form-item label="仓库代码">
                  <el-input
                    v-model.trim="searchCriteria.dispatchAddressCode"
                    placeholder="仓库代码"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="参考号">
                  <el-input
                    v-model.trim="searchCriteria.referenceNo"
                    placeholder="参考号"
                  />
                </el-form-item>
                <el-form-item label="shipmentID">
                  <el-input
                    v-model.trim="searchCriteria.shipmentID"
                    placeholder="shipmentID"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item label="中文品名">
                  <el-input
                    v-model.trim="searchCriteria.declareNameCn"
                    placeholder="中文品名"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>

          <el-col :span="4" class="text-right">
            <el-button type="primary" size="mini" @click="onSubmit">
              查询
            </el-button>
            <el-button type="primary" size="mini" @click="onReset">
              重置
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card class="margin-top">
      <div class="flex align-center justify-between padding-bottom-sm">
        <el-pagination
          :current-page="currentPage"
          :page-sizes="[20, 40, 60, 80, 100]"
          :page-size="pageSize"
          layout="prev, pager, next, jumper, sizes,total"
          :total="pageTotal"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
        <el-button-group>
          <el-button size="mini" type="primary" @click="onSendingn">
            批量交寄
          </el-button>
          <el-button size="mini" type="primary" @click="onCustomsDeclaration">
            合并报关
          </el-button>
          <el-button
            size="mini"
            type="primary"
            @click="cancelCustomsDeclaration"
          >
            取消合并报关
          </el-button>
          <el-button size="mini" type="primary" @click="onPrint">
            批量打印运单标签
          </el-button>
        </el-button-group>
      </div>

      <el-table
        class="table-box"
        :data="tableData"
        style="width: 100%"
        size="mini"
        :row-class-name="tableRowClassName"
        @select-all="selectAll"
        @select="selectItem"
      >
        <el-table-column type="selection" align="center" />
        <el-table-column type="index" label="序号" />
        <ex-table-column
          v-for="(item, index) in tableColumns"
          :key="index"
          :label="item.children[0].label"
          :prop="item.children[0].prop"
          :fit-header="true"
          :auto-fit="true"
        >
          <template v-if="item.children.length > 1">
            <ex-table-column
              :auto-fit="true"
              :label="item.children[1].label"
              :prop="item.children[1].prop"
              :fit-header="true"
            >
              <template slot-scope="scope">
                <div>
                  <template
                    v-if="showWarehouseInfo && item.children[0].prop === 'customerTotalPackages'"
                  >
                    <el-link @click="getPackagesInfo(scope)">{{
                      scope.row[`${item.children[0].prop}`]
                    }}</el-link>
                  </template>
                  <template v-else>
                    {{ scope.row[`${item.children[0].prop}`] }}
                  </template>
                </div>
                <div v-if="!showWarehouseInfo && ['inStockActualWeight','inStockVolume','inStockChargedWeight'].includes(item.children[1].prop)" />
                <div v-else>{{ scope.row[`${item.children[1].prop}`] }}</div>
              </template>
            </ex-table-column>
          </template>
          <template slot-scope="scope">
            <template v-if="item.children[0].prop === 'abroadWaybillNo'">
              <el-link @click="goAbroad(scope)">
                {{ scope.row[`${item.children[0].prop}`] }}
              </el-link>
            </template>
            <el-popover
              v-if="scope.column.property == 'trackNumber2'"
              trigger="hover"
              placement="bottom"
            >
              <p
                v-if="
                  scope.row.trackNumber !== null &&
                    scope.row.track1Type !== null
                "
              >
                {{ scope.row.trackNumber }}&nbsp;{{ scope.row.track1Type }}
              </p>
              <p
                v-if="
                  scope.row.trackNumber2 !== null &&
                    scope.row.track2Type !== null
                "
              >
                {{ scope.row.trackNumber2 }}&nbsp;{{ scope.row.track2Type }}
              </p>
              <p
                v-if="
                  scope.row.trackNumber3 !== null &&
                    scope.row.track3Type !== null
                "
              >
                {{ scope.row.trackNumber3 }}&nbsp;{{ scope.row.track3Type }}
              </p>

              <div slot="reference">
                <div>{{ scope.row.trackNumber }}</div>
                <div>{{ scope.row.trackNumber2 }}</div>
              </div>
            </el-popover>
          </template>
        </ex-table-column>

        <el-table-column
          :auto-fit="true"
          fixed="right"
          label="操作"
          width="240"
        >
          <template slot-scope="scope">
            <div class="flex align-center">
              <el-tooltip
                class="item margin-left-xs"
                effect="dark"
                :content="
                  scope.row.abroadWaybillNo ? '取消中转下单' : '中转下单'
                "
                placement="top"
              >
                <i
                  class="operation-icon el-icon-guide pointer"
                  :class="scope.row.abroadWaybillNo ? 'text-red' : 'text-grey'"
                  @click="transferAboradWaybill(scope.row)"
                />
              </el-tooltip>
              <el-tooltip
                class="item margin-left-xs"
                effect="dark"
                content="起运港账单状态,灰色未出账单;绿色已出账单"
                placement="top"
              >
                <img
                  v-if="scope.row.billStatus === 1"
                  src="@/assets/images/yes_bill_status.png"
                >
                <img
                  v-if="scope.row.billStatus != 1"
                  src="@/assets/images/no_bill_status.png"
                >
              </el-tooltip>
              <el-tooltip
                v-if="
                  scope.row.countryId == 330 &&
                    scope.row.isTaxFarming == 0 &&
                    (scope.row.purposeWarehouseType === 100 ||
                      scope.row.purposeWarehouseType === 400)
                "
                class="item margin-left-xs"
                effect="dark"
                content="是否清关递延变量,灰色否，黑色是"
                placement="top"
              >
                <img
                  v-if="scope.row.isPVA === 1"
                  src="@/assets/images/is_pva_1.png"
                >
                <img
                  v-if="scope.row.isPVA != 1"
                  src="@/assets/images/is_pva_0.png"
                >
              </el-tooltip>
              <el-tooltip
                v-if="scope.row.mergerDeclarationNo"
                class="item margin-left-xs"
                effect="dark"
                content="合并报关单"
                placement="top"
              >
                <img src="@/assets/images/merger_declaration.jpeg">
              </el-tooltip>
              <el-tooltip
                v-if="scope.row.status === 10"
                class="item margin-left-xs"
                effect="dark"
                content="编辑"
                placement="top"
              >
                <i
                  class="el-icon-edit-outline operation-icon pointer"
                  @click="colEdit(scope.row)"
                />
              </el-tooltip>
              <el-tooltip
                v-if="scope.row.status === 10"
                class="item margin-left-xs"
                effect="dark"
                content="删除"
                placement="top"
              >
                <i
                  class="el-icon-close operation-icon pointer"
                  @click="colDel(scope.row)"
                />
              </el-tooltip>
              <el-tooltip
                class="item margin-left-xs"
                effect="dark"
                content="查看订单详情"
                placement="top"
              >
                <i
                  class="el-icon-zoom-in operation-icon pointer"
                  @click="colCheckDetails(scope.row)"
                />
              </el-tooltip>
              <el-tooltip
                class="item margin-left-xs"
                effect="dark"
                content="复制"
                placement="top"
              >
                <i
                  class="el-icon-document-copy operation-icon pointer"
                  @click="colEdit(scope.row, 'copy')"
                />
              </el-tooltip>
              <el-tooltip
                class="item margin-left-xs"
                effect="dark"
                content="下载已上传装箱单"
                placement="top"
              >
                <i
                  class="el-icon-download operation-icon pointer"
                  @click="colDownload(scope.row)"
                />
              </el-tooltip>
              <el-popover
                class="item margin-left-xs"
                placement="top"
                trigger="hover"
              >
                <div>
                  <el-divider content-position="left">
                    请选择预览打印的方式(A4纸每页打印6个标签)
                  </el-divider>
                  <el-button
                    size="mini"
                    type="success"
                    @click="colPrinter({ row: scope.row, index: 0 })"
                  >
                    10*10
                  </el-button>
                  <el-button
                    size="mini"
                    type="success"
                    @click="colPrinter({ row: scope.row, index: 1 })"
                  >
                    10*10(PDF)
                  </el-button>
                  <el-button
                    size="mini"
                    type="success"
                    @click="colPrinter({ row: scope.row, index: 2 })"
                  >
                    10*8(PDF)
                  </el-button>
                  <el-button
                    size="mini"
                    type="success"
                    @click="colPrinter({ row: scope.row, index: 3 })"
                  >
                    A4(PDF)
                  </el-button>
                </div>

                <div slot="reference">
                  <i class="el-icon-printer operation-icon" />
                </div>
              </el-popover>
              <el-tooltip
                v-if="scope.row.status === 20"
                class="item margin-left-xs"
                effect="dark"
                content="打回待确认"
                placement="top"
              >
                <svg-icon
                  class="operation-icon pointer"
                  name="return"
                  @click="colReturn(scope.row)"
                />
              </el-tooltip>
              <el-tooltip
                v-if="
                  scope.row.isCustomerDeclaration == 1 && scope.row.status <= 40
                "
                class="item margin-left-xs"
                effect="dark"
                content="上传报关资料"
                placement="top"
              >
                <i
                  class="operation-icon el-icon-upload2 pointer"
                  name="return"
                  @click="uploadCustomsInfo(scope.row)"
                />
              </el-tooltip>
              <el-tooltip
                v-if="scope.row.purposeWarehouseType === 500"
                class="item margin-left-xs"
                effect="dark"
                content="上传CDA资料"
                placement="top"
              >
                <i
                  class="operation-icon el-icon-upload2 pointer"
                  @click="uploadCDA(scope.row)"
                />
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog title="提示" :visible.sync="batchPrintDialog" width="30%">
      <div class="text-center">
        <div class="margin-bottom">
          请选择预览打印的方式(A4纸每页打印6个标签)
        </div>

        <el-button
          size="mini"
          type="success"
          @click="colPrinter({ index: 0, batch: true })"
        >
          10*10
        </el-button>
        <el-button
          size="mini"
          type="success"
          @click="colPrinter({ index: 1, batch: true })"
        >
          10*10(PDF)
        </el-button>
        <el-button
          size="mini"
          type="success"
          @click="colPrinter({ index: 2, batch: true })"
        >
          10*8(PDF)
        </el-button>
        <el-button
          size="mini"
          type="success"
          @click="colPrinter({ index: 3, batch: true })"
        >
          A4(PDF)
        </el-button>
      </div>
    </el-dialog>

    <el-dialog
      :title="importInfo.title"
      :visible.sync="uploadDialog"
      width="50%"
    >
      <el-upload
        ref="upload"
        class="upload-demo"
        drag
        action="#"
        :limit="1"
        :auto-upload="true"
        :file-list="fileList"
        :http-request="uploadFn"
        :on-change="onChange"
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>

        <!-- <el-button slot="trigger" size="small" type="primary">选取文件</el-button> -->
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="closeUploadDialog">取 消</el-button>
        <el-button size="mini" type="primary" @click="enterUploadDialog">
          确 定
        </el-button>
      </div>
    </el-dialog>
    <el-dialog

      :visible.sync="showPackages"
      width="50%"
      :before-close="closePackagesBox"
    >
      <div slot="title">
        <span class="title-icon">入库单</span>
        <span class="text-red margin-left pointer" @click="exportExcel">导出</span>
      </div>
      <!-- <TableModule
        :table-columns="packagesColumns"
        :table-data="packagesData"
        need-serial-number
      /> -->
      <el-table
        size="mini"
        :data="packagesData"
        border
        :summary-method="getSummaries"
        show-summary
      >
        <el-table-column type="index" width="50" />
        <el-table-column
          v-for="(item, index) in packagesColumns"
          :key="index"
          :width="columnWidth(item.prop)"
          :prop="item.prop"
          :label="item.label"
        />
      </el-table>
    </el-dialog>
  </section>
</template>

<script>
import { mapGetters } from 'vuex'

import {
  initListPage,
  listPage,
  deleteWaybillById,
  replyWaybill,
  createPdfLabel10x10,
  createPdfLabel10x8,
  createPdfLabelA4,
  printWaybillLabel,
  fetchLiquidationInvoiceMeasurementUnit,
  mergerDeclaration,
  cancelMergerDeclaration,
  exportLiquidationPacking,
  uploadWaybillFile,
  saveWaybillFile,
  querySubWaybill,
  searchOrderByWaybillNo,
  transferCreateAboradWaybill,
  cancelTransferAboradWaybill,
  downLoadWarehouse
} from '@/api/waybill'

import globalData from '@/utils/config'
import { getLodop } from '@/utils/LodopFuncs'
import { compileStr } from '@/utils'
export default {
  name: 'WaybillList',

  //  props: ['status'],
  data() {
    return {
      showPackages: false,
      batchPrintDialog: false,
      uploadDialog: false,
      fileList: [],
      status: 0,
      importInfo: {
        title: '上传CDA资料',
        actionUrl: '/seaair/waybills/uploadWaybillFile',
        fileTypeName: 1
      },
      uploadInfo: {},
      selection: [],
      searchCriteria: {
        status: [0],
        inStockChannel: '',
        waybillNo: '',
        trackNumber: '',
        referenceNo: '',
        countryId: '',
        declareNameCn: '',
        sku: '',
        dispatchAddressCode: '',
        shipmentID: ''
      },
      waybillBtn: [
        {
          name: 'waybillAll',
          status: 0,
          number: 0
        },
        {
          name: 'waitForConfirm',
          status: 10,
          number: 0
        },
        {
          name: 'waitForDealSend',
          status: 20,
          number: 0
        },
        {
          name: 'waitForOutStock',
          status: 40,
          number: 0
        },
        {
          name: 'waitForSign',
          status: 140,
          number: 0
        },
        {
          name: 'alrSeadySigned',
          status: 999,
          number: 0
        },
        {
          name: 'problematic',
          status: 900,
          number: 0
        },
        {
          name: 'alrSeadyReturned',
          status: -20,
          number: 0
        }
      ],
      currentPage: 1,
      pageSize: 20,
      pageTotal: 0,
      tableColumns: [
        {
          children: [
            { label: '运单号', prop: 'waybillNo', type: 'string' },
            { label: '参考号', prop: 'referenceNo', type: 'string' }
          ]
        },
        {
          children: [
            { label: '状态', prop: 'statusName', type: 'string' },
            { label: '收货地', prop: 'storageLocationName', type: 'string' }
          ]
        },

        {
          children: [
            { label: '追踪号1', prop: 'trackNumber', type: 'string' },
            { label: '追踪号2', prop: 'trackNumber2', type: 'string' }
          ]
        },
        {
          children: [
            { label: '目的国', prop: 'countryName', type: 'string' },
            { label: '派送地址', prop: 'dispatchAddressCode', type: 'string' }
          ]
        },
        {
          children: [
            { label: '入库渠道', prop: 'customerChannelMap', type: 'string' },
            { label: '申报总额', prop: 'totalDeclareValueStr', type: 'string' }
          ]
        },
        {
          children: [
            { label: '预报实重', prop: 'customerActualWeight', type: 'string' },
            { label: '入库实重', prop: 'inStockActualWeight', type: 'string' }
          ]
        },
        {
          children: [
            { label: '预报体积', prop: 'customerVolume', type: 'string' },
            { label: '入库体积', prop: 'inStockVolume', type: 'string' }
          ]
        },
        {
          children: [
            {
              label: '预报计费重',
              prop: 'customerChargedWeight',
              type: 'string'
            },
            {
              label: '入库计费重',
              prop: 'inStockChargedWeight',
              type: 'string'
            }
          ]
        },
        {
          children: [
            {
              label: '预报件数',
              prop: 'customerTotalPackages',
              type: 'string'
            },
            { label: '入库件数', prop: 'inStockTotalPackages', type: 'string' }
          ]
        },

        {
          children: [
            { label: '入库时间', prop: 'inStockTime', type: 'string' },
            { label: '出库时间', prop: 'outStockTime', type: 'string' }
          ]
        },
        {
          children: [
            { label: '渠道能力', prop: 'channelCapacity', type: 'string' },
            { label: '国内分区', prop: 'countryStateName', type: 'string' }
          ]
        },
        {
          children: [
            { label: '海外仓运单', prop: 'abroadWaybillNo', type: 'string' }
          ]
        }
      ],
      tableData: [],
      printList: [],
      packagesColumns: [
        {
          prop: 'boxNo',
          label: '外箱号'
        },
        {
          prop: 'trackNumber',
          label: '追踪号'
        },
        {
          prop: 'weight',
          label: '重量'
        },
        {
          prop: 'length',
          label: '长'
        },
        {
          prop: 'width',
          label: '宽'
        },
        {
          prop: 'height',
          label: '高'
        },
        {
          prop: 'totalVolum',
          label: '体积'
        },
        {
          prop: 'volumeWeight',
          label: '体积重'
        },
        {
          prop: 'chargedWeight',
          label: '计费重'
        }
      ],
      packagesData: [{}, {}],
      showPackagesWaybillId: ''
    }
  },
  computed: {
    ...mapGetters(['publicData', 'showWarehouseInfo'])
  },
  created() {
    if (this.$route.params && this.$route.params.status) {
      this.status = this.$route.params.status
    }
  },

  mounted() {
    console.log('this.showWarehouseInfo :>> ', this.showWarehouseInfo)
    this.init()
  },

  methods: {
    async init() {
      const dataCont = await initListPage({})
      for (var key in dataCont) {
        this.waybillBtn.forEach(data => {
          if (data.status == key) {
            data.number = dataCont[key]
          }
        })
      }
      if (!isNaN(this.status)) {
        this.searchCriteria.status[0] = this.status
      }
      this.queryList()
    },

    columnWidth(prop) {
      let widthStr = ''
      if (prop === 'boxNo') {
        widthStr = 160
      } else if (prop === 'trackNumber') {
        widthStr = 160
      }
      return widthStr
    },
    async queryList() {
      this.tableData = []
      this.searchCriteria.pageSize = this.pageSize
      this.searchCriteria.currentPage = this.currentPage
      const list = await listPage(this.searchCriteria)
      this.tableData = list.datas
      this.pageTotal = list.count
      const statusMap = this.publicData.waybillStatusMap
      const channelMap = this.publicData.channelMap
      const countryMap = this.publicData.countryMap
      const countryStateMap = this.publicData.countryStateMap
      if (this.tableData !== null) {
        this.tableData.forEach(data => {
          if (data.status) {
            data.statusName = this.$t('waybill.' + statusMap[data.status])
          }
          if (data.declareValueCurrency && data.totalDeclareValue) {
            data.totalDeclareValueStr =
              data.totalDeclareValue + '(' + data.declareValueCurrency + ')'
          }

          if (data.inStockChannel) {
            data.customerChannelMap = channelMap[data.inStockChannel]
          }

          if (data.countryId) {
            data.countryName = countryMap[data.countryId]
          }

          if (data.provinceId) {
            data.countryStateName = countryStateMap[data.provinceId]
          }
          if (data.storageLocation) {
            data.storageLocationName = this.publicData.storageLocationMap[
              data.storageLocation
            ]
          }

          if (data.channelCapacity) {
            const arr = []
            for (const i of data.channelCapacity.split(',')) {
              arr.push(this.publicData.channelAbilitysMap[i])
            }
            data.channelCapacity = arr.join(',')
          }
        })
      }
      this.$store.dispatch('app/toggleDialog', false)
    },
    getWaybill(status) {
      this.$store.dispatch('app/toggleDialog', true)
      this.status = status
      this.searchCriteria.status[0] = status
      this.queryList()
    },
    handleSizeChange(val) {
      this.$store.dispatch('app/toggleDialog', true)
      this.pageSize = val
      this.queryList()
    },
    handleCurrentChange(val) {
      this.$store.dispatch('app/toggleDialog', true)
      this.currentPage = val
      this.queryList()
    },
    async onSubmit() {
      this.$store.dispatch('app/toggleDialog', true)
      this.currentPage = 1
      this.queryList()
    },
    onReset() {
      this.$store.dispatch('app/toggleDialog', true)
      this.currentPage = 1
      this.searchCriteria = {
        inStockChannel: '',
        waybillNo: '',
        trackNumber: '',
        referenceNo: '',
        countryId: '',
        declareNameCn: ''
      }
      this.queryList()
    },
    async onSendingn() {
      if (this.checkSelect()) {
        this.$store.dispatch('app/toggleDialog', true)
        const waybillIds = []
        this.selection.forEach(data => {
          waybillIds.push(data.id)
        })
        const params = {
          waybillIds: waybillIds
        }
        const { code, message } = await fetchLiquidationInvoiceMeasurementUnit(
          params
        )

        if (code === 200) {
          this.$message({
            message: '提交成功!',
            type: 'success'
          })
          this.queryList()
        } else {
          this.$message.error(message)
        }
        this.$store.dispatch('app/toggleDialog', false)
      }
    },
    async onCustomsDeclaration() {
      if (this.checkSelect()) {
        this.$store.dispatch('app/toggleDialog', true)
        const waybillIds = []
        this.selection.forEach(data => {
          waybillIds.push(data.id)
        })
        const params = {
          waybillIds: waybillIds
        }
        const { code, message } = await mergerDeclaration(params)

        if (code === 200) {
          this.$message({
            message: '提交成功!',
            type: 'success'
          })
          this.queryList()
        } else {
          this.$message.error(message)
        }
        this.$store.dispatch('app/toggleDialog', false)
      }
    },
    async cancelCustomsDeclaration() {
      if (this.checkSelect()) {
        this.$store.dispatch('app/toggleDialog', true)
        const waybillIds = []
        this.selection.forEach(data => {
          waybillIds.push(data.id)
        })
        const params = {
          waybillIds: waybillIds
        }
        const { code, message } = await cancelMergerDeclaration(params)

        if (code === 200) {
          this.$message({
            message: '提交成功!',
            type: 'success'
          })
          this.queryList()
        } else {
          this.$message.error(message)
        }
        this.$store.dispatch('app/toggleDialog', false)
      }
    },
    onPrint() {
      if (this.checkSelect()) {
        this.batchPrintDialog = true
      }
    },
    selectItem(selection, row) {
      this.selection = selection
    },
    selectAll(selection) {
      this.selection = selection
    },
    colEdit(row, type) {
      const a = 'ZX,AIR'
      const s = 'FCL,LCL'
      // const e = '99'

      let name = ''
      let tab = ''
      if (a.indexOf(row.shippingWay) > -1 && row.waybillType !== 'C') {
        // 空运下单
        name = 'orderToAirFreight'
      } else if (s.indexOf(row.shippingWay) > -1 && row.waybillType !== 'C') {
        // 海运下单
        name = 'orderToSeaFreight'
      } else if (row.waybillType === 'C') {
        // 港到港下单
        name = 'addAirSeag2gwaybill'
      } else {
        // 快递下单
        name = 'orderToExpressDelivery'
      }
      if (row.ordersByFba === 1) {
        // 快捷下单
        tab = 'quickOrder'
      } else {
        // 标准下单
        tab = 'standardOrder'
      }

      const routeUrl = this.$router.resolve({
        path: `/waybillManagement/${name}`,
        query: {
          tab: tab,
          id: compileStr(row.id.toString()),
          isCopy: type ? 1 : 0
        }
      })
      window.open(routeUrl.href, '_blank')
    },
    colDel(id) {
      this.$confirm('确定要删除吗？')
        .then(_ => {
          this.delteRow(id)
        })
        .catch(_ => {})
    },
    async delteRow(row) {
      this.$store.dispatch('app/toggleDialog', true)
      const { code, message } = await deleteWaybillById({ id: row.id })

      if (code === 200) {
        this.$message({
          message: '删除成功!',
          type: 'success'
        })
        this.queryList()
      } else {
        this.$message.error(message)
      }
      this.$store.dispatch('app/toggleDialog', false)
    },
    async colDownload(row) {
      this.$store.dispatch('app/toggleDialog', true)

      const data = await exportLiquidationPacking({ id: row.id })

      if (data.path) {
        window.open(globalData.fileUrl + data.path)
      } else {
        this.$message.error(data.errorMesage || '下载失败')
      }
      this.$store.dispatch('app/toggleDialog', false)
    },
    async colReturn(row) {
      this.$store.dispatch('app/toggleDialog', true)
      const { code, message } = await replyWaybill({ id: row.id })

      if (code === 200) {
        this.$message({
          message: '运单已打回待确认!',
          type: 'success'
        })
        this.queryList()
      } else {
        this.$message.error(message)
        this.$store.dispatch('app/toggleDialog', false)
      }
    },
    async colPrinter({ row, index, batch }) {
      let list = []
      if (batch) {
        for (const i of this.selection) {
          list.push(i.id)
        }
      } else {
        list = [row.id]
      }
      if (index !== 0) {
        this.$store.dispatch('app/toggleDialog', true)
      }
      let data
      switch (index) {
        case 0:
          data = await printWaybillLabel({
            waybillIds: list
          })
          if (data.code === 200) {
            if (data.data.length > 0) {
              // this.printList = data.data
              this.getLodopFn(data.data)
            } else {
              this.$message.error('暂无数据')
            }
          } else {
            this.$message.error(data.message || '请求失败')
          }
          this.$store.dispatch('app/toggleDialog', false)
          break
        case 1:
          data = await createPdfLabel10x10({
            waybillIds: list
          })
          if (data) {
            this.$message({
              message:
                '已为您打开文件下载页面，如果页面未跳转，请检查弹出窗口是否被浏览器拦截',
              type: 'success',
              duration: 5000,
              showClose: true
            })
            window.open(globalData.fileUrl + data)
          } else {
            this.$message.error('暂无数据')
          }
          this.$store.dispatch('app/toggleDialog', false)
          break
        case 2:
          data = await createPdfLabel10x8({
            waybillIds: list
          })
          if (data) {
            this.$message({
              message:
                '已为您打开文件下载页面，如果页面未跳转，请检查弹出窗口是否被浏览器拦截',
              type: 'success',
              duration: 5000,
              showClose: true
            })
            window.open(globalData.fileUrl + data)
          } else {
            this.$message.error('暂无数据')
          }
          this.$store.dispatch('app/toggleDialog', false)
          break
        case 3:
          data = await createPdfLabelA4({
            waybillIds: list
          })
          if (data) {
            this.$message({
              message:
                '已为您打开文件下载页面，如果页面未跳转，请检查弹出窗口是否被浏览器拦截',
              type: 'success',
              duration: 5000,
              showClose: true
            })
            window.open(globalData.fileUrl + data)
          } else {
            this.$message.error('暂无数据')
          }
          this.$store.dispatch('app/toggleDialog', false)
          break
      }

      // console.log('data :>> ', data)
    },
    tableRowClassName({ row, rowIndex }) {
      if (row.status && row.status === -10) {
        return 'warning-row'
      }
      return ''
    },
    getLodopFn(htmls, printName) {
      const Lodop = getLodop()
      if (!htmls) {
        return
      }
      if (!Lodop) {
        return
      }
      console.log('Lodop :>> ', Lodop)
      LODOP.PRINT_INIT('打印订单信息')
      LODOP.SET_PRINT_PAGESIZE(1, 0, 0, 'A4')
      var pageNum = Math.ceil(htmls.length / 6)
      var htmlLength = htmls.length
      for (var j = 0; j < pageNum; j++) {
        var n = 6 * j
        for (var m = 0; m < 6; m++) {
          var k = m + n
          if (k >= htmlLength) {
            continue
          }
          var html = htmls[k]
          if (m == 0) {
            LODOP.ADD_PRINT_HTM(0, 0, '94mm', '94mm', html) // Top,Left,Width,Height,strHtmlContent
          } else if (m == 1) {
            LODOP.ADD_PRINT_HTM(0, '100mm', '94mm', '94mm', html)
          } else if (m == 2) {
            LODOP.ADD_PRINT_HTM('97mm', 0, '94mm', '94mm', html)
          } else if (m == 3) {
            LODOP.ADD_PRINT_HTM('97mm', '100mm', '94mm', '94mm', html)
          } else if (m == 4) {
            LODOP.ADD_PRINT_HTM('194mm', 0, '94mm', '94mm', html)
          } else if (m == 5) {
            LODOP.ADD_PRINT_HTM('194mm', '100mm', '94mm', '94mm', html)
          }
          var body = document.querySelector('body')
          body.append(
            "<div id='templateContentHtml' style='display:none'>" +
              html +
              '</div>'
          )
          var barCodes = document.getElementsByName('barcode')
          for (var i = 0; i < barCodes.length; i++) {
            var barCode = barCodes[i]
            var value = barCode.getAttribute('value')
            var values
            if (value.indexOf('|') >= 0) {
              values = barCode.getAttribute('value').split('|')
            } else {
              values = barCode.getAttribute('value').split('-')
            }
            var reg = new RegExp('mm', 'g')
            if (values[5] != '' && values[5] != null) {
              var codes = values[5].split('+')
              var serialNo = codes[0].substring(6, codes[0].length)
              var top = values[0].replace(reg, '').trim()
              var left = values[1].replace(reg, '').trim()
              left = parseFloat(left)
              top = parseFloat(top)
              if (m == 0) {
                if (i == 1) {
                  LODOP.SET_PRINT_STYLE('FontSize', 10)
                  LODOP.SET_PRINT_STYLE('Bold', 1)
                  LODOP.ADD_PRINT_TEXT(
                    295,
                    left - 5 + 'mm',
                    60,
                    10,
                    codes[0].substring(0, 6)
                  )
                  LODOP.SET_PRINT_STYLE('FontSize', 16)
                  LODOP.SET_PRINT_STYLE('Bold', 1)
                  LODOP.ADD_PRINT_TEXT(290, left + 9 + 'mm', 100, 10, serialNo)
                  LODOP.SET_PRINT_STYLE('FontSize', 10)
                  LODOP.SET_PRINT_STYLE('Bold', 1)
                  LODOP.ADD_PRINT_TEXT(
                    295,
                    left + 29 + 'mm',
                    40,
                    10,
                    '+' + codes[1]
                  )
                }
                left = left - 5 + 'mm'
                LODOP.ADD_PRINT_BARCODE(
                  values[0],
                  left,
                  values[2],
                  values[3],
                  values[4],
                  values[5]
                )
              } else if (m == 1) {
                if (i == 1) {
                  LODOP.SET_PRINT_STYLE('FontSize', 10)
                  LODOP.SET_PRINT_STYLE('Bold', 1)
                  LODOP.ADD_PRINT_TEXT(
                    295,
                    left + 95 + 'mm',
                    60,
                    10,
                    codes[0].substring(0, 6)
                  )
                  LODOP.SET_PRINT_STYLE('FontSize', 16)
                  LODOP.SET_PRINT_STYLE('Bold', 1)
                  LODOP.ADD_PRINT_TEXT(
                    290,
                    left + 109 + 'mm',
                    100,
                    10,
                    serialNo
                  )
                  LODOP.SET_PRINT_STYLE('FontSize', 10)
                  LODOP.SET_PRINT_STYLE('Bold', 1)
                  LODOP.ADD_PRINT_TEXT(
                    295,
                    left + 129 + 'mm',
                    40,
                    10,
                    '+' + codes[1]
                  )
                }
                left = left + 95 + 'mm'
                LODOP.ADD_PRINT_BARCODE(
                  values[0],
                  left,
                  values[2],
                  values[3],
                  values[4],
                  values[5]
                )
              } else if (m == 2) {
                if (i == 1) {
                  var codes = values[5].split('+')
                  var serialNo = codes[0].substring(6, codes[0].length)
                  LODOP.SET_PRINT_STYLE('FontSize', 10)
                  LODOP.SET_PRINT_STYLE('Bold', 1)
                  LODOP.ADD_PRINT_TEXT(
                    661,
                    left - 5 + 'mm',
                    60,
                    10,
                    codes[0].substring(0, 6)
                  )
                  LODOP.SET_PRINT_STYLE('FontSize', 16)
                  LODOP.SET_PRINT_STYLE('Bold', 1)
                  LODOP.ADD_PRINT_TEXT(656, left + 9 + 'mm', 100, 10, serialNo)
                  LODOP.SET_PRINT_STYLE('FontSize', 10)
                  LODOP.SET_PRINT_STYLE('Bold', 1)
                  LODOP.ADD_PRINT_TEXT(
                    661,
                    left + 29 + 'mm',
                    40,
                    10,
                    '+' + codes[1]
                  )
                }
                top = top + 97 + 'mm'
                left = left - 5 + 'mm'
                LODOP.ADD_PRINT_BARCODE(
                  top,
                  left,
                  values[2],
                  values[3],
                  values[4],
                  values[5]
                )
              } else if (m == 3) {
                if (i == 1) {
                  var codes = values[5].split('+')
                  var serialNo = codes[0].substring(6, codes[0].length)
                  LODOP.SET_PRINT_STYLE('FontSize', 10)
                  LODOP.SET_PRINT_STYLE('Bold', 1)
                  LODOP.ADD_PRINT_TEXT(
                    661,
                    left + 95 + 'mm',
                    60,
                    10,
                    codes[0].substring(0, 6)
                  )
                  LODOP.SET_PRINT_STYLE('FontSize', 16)
                  LODOP.SET_PRINT_STYLE('Bold', 1)
                  LODOP.ADD_PRINT_TEXT(
                    656,
                    left + 109 + 'mm',
                    100,
                    10,
                    serialNo
                  )
                  LODOP.SET_PRINT_STYLE('FontSize', 10)
                  LODOP.SET_PRINT_STYLE('Bold', 1)
                  LODOP.ADD_PRINT_TEXT(
                    661,
                    left + 129 + 'mm',
                    40,
                    10,
                    '+' + codes[1]
                  )
                }
                left = left + 95 + 'mm'
                top = top + 97 + 'mm'
                LODOP.ADD_PRINT_BARCODE(
                  top,
                  left,
                  values[2],
                  values[3],
                  values[4],
                  values[5]
                )
              } else if (m == 4) {
                if (i == 1) {
                  var codes = values[5].split('+')
                  var serialNo = codes[0].substring(6, codes[0].length)
                  LODOP.SET_PRINT_STYLE('FontSize', 10)
                  LODOP.SET_PRINT_STYLE('Bold', 1)
                  LODOP.ADD_PRINT_TEXT(
                    1028,
                    left - 5 + 'mm',
                    60,
                    10,
                    codes[0].substring(0, 6)
                  )
                  LODOP.SET_PRINT_STYLE('FontSize', 14)
                  LODOP.SET_PRINT_STYLE('Bold', 1)
                  LODOP.ADD_PRINT_TEXT(1024, left + 9 + 'mm', 100, 10, serialNo)
                  LODOP.SET_PRINT_STYLE('FontSize', 10)
                  LODOP.SET_PRINT_STYLE('Bold', 1)
                  LODOP.ADD_PRINT_TEXT(
                    1028,
                    left + 28 + 'mm',
                    40,
                    10,
                    '+' + codes[1]
                  )
                }
                top = top + 194 + 'mm'
                left = left - 5 + 'mm'
                LODOP.ADD_PRINT_BARCODE(
                  top,
                  left,
                  values[2],
                  values[3],
                  values[4],
                  values[5]
                )
              } else if (m == 5) {
                if (i == 1) {
                  var codes = values[5].split('+')
                  var serialNo = codes[0].substring(6, codes[0].length)
                  LODOP.SET_PRINT_STYLE('FontSize', 10)
                  LODOP.SET_PRINT_STYLE('Bold', 1)
                  LODOP.ADD_PRINT_TEXT(
                    1028,
                    left + 95 + 'mm',
                    60,
                    10,
                    codes[0].substring(0, 6)
                  )
                  LODOP.SET_PRINT_STYLE('FontSize', 14)
                  LODOP.SET_PRINT_STYLE('Bold', 1)
                  LODOP.ADD_PRINT_TEXT(
                    1024,
                    left + 109 + 'mm',
                    100,
                    10,
                    serialNo
                  )
                  LODOP.SET_PRINT_STYLE('FontSize', 10)
                  LODOP.SET_PRINT_STYLE('Bold', 1)
                  LODOP.ADD_PRINT_TEXT(
                    1028,
                    left + 128 + 'mm',
                    40,
                    10,
                    '+' + codes[1]
                  )
                }
                left = left + 95 + 'mm'
                top = top + 194 + 'mm'
                LODOP.ADD_PRINT_BARCODE(
                  top,
                  left,
                  values[2],
                  values[3],
                  values[4],
                  values[5]
                )
              }
            }
            if (
              values[6] == 1 ||
              typeof values[6] === 'undefined' ||
              values[6] == ''
            ) {
              if (i == 1) {
                LODOP.SET_PRINT_STYLEA(0, 'ShowBarText', 0)
              } else {
                LODOP.SET_PRINT_STYLEA(0, 'ShowBarText', 1)
              }
              LODOP.SET_PRINT_STYLEA(0, 'AlignJustify', 2)
            } else {
              LODOP.SET_PRINT_STYLEA(0, 'ShowBarText', 0)
            }
          }
          // $("#templateContentHtml").remove();
          var templateContentHtml = document.querySelector(
            'templateContentHtml'
          )
          this.removeDom(templateContentHtml)
        }
        LODOP.NewPage() // 分页
      }
      if (printName != null && printName != '') {
        LODOP.SET_PRINTER_INDEX(printName)
      } else {
        LODOP.PREVIEW()
      }
    },
    // 移除节点
    removeDom(model) {
      var self = this
      if (self.$parent.model) {
        self.$parent.model.children.forEach((item, index) => {
          if (item.name == model.name) {
            self.$parent.model.children.splice(index, 1)
          }
        })
      }
    },

    colCheckDetails(row) {
      const routeUrl = this.$router.resolve({
        name: 'WaybillDetails',
        params: { id: compileStr(row.id.toString()) }
      })

      window.open(routeUrl.href, '_blank')
    },
    checkSelect() {
      if (this.selection.length === 0) {
        this.$message.error('请先选择运单!')
        return false
      } else {
        return true
      }
    },

    async enterUploadDialog() {
      const { code } = await saveWaybillFile(this.uploadInfo)
      if (code === 200) {
        this.$message.success('上传成功!')
      } else {
        this.$message.error('上传失败!')
      }
      this.closeUploadDialog()
    },
    closeUploadDialog() {
      this.uploadDialog = false
      this.importInfo.title = ''
      this.uploadInfo = {}
      this.fileList = []
    },
    beforeUpload(file, fileList) {
      const isLt50M = file.size / 1024 / 1024 < 50

      if (!isLt50M) {
        this.$message.error('上传文件大小不能超过 50MB!')
        return false
      }
      return true
    },
    async uploadFn(params) {
      console.log('params', params)
      if (!this.beforeUpload(params.file)) return
      const formData = new FormData()
      // 通过 FormData 对象上传文件
      formData.append(this.fileName, params.file)

      const data = await uploadWaybillFile(formData)
      this.uploadInfo.fileName = params.file.name
      this.uploadInfo.fileUrl = data.fileUrl
    },
    onChange(file, fileList) {
      console.log('onChange', file, fileList)
      this.fileList = fileList
    },
    uploadCustomsInfo(row) {
      this.uploadDialog = true
      this.importInfo.title = '上传报关资料'
      this.uploadInfo.fileTypeName = '客户报关资料'
      this.uploadInfo.waybillId = row.id
    },
    uploadCDA(row) {
      this.uploadDialog = true
      this.importInfo.title = '上传CDA资料'
      this.uploadInfo.fileTypeName = 'CDA'
      this.uploadInfo.waybillId = row.id
    },
    closePackagesBox() {
      this.showPackages = false
      this.packagesData = []
    },
    async getPackagesInfo(s) {
      this.showPackages = true
      const { data } = await querySubWaybill({ waybillId: s.row.id })
      if (Array.isArray(data)) {
        this.packagesData = data
        this.showPackagesWaybillId = s.row.id
      } else {
        this.$message.error('获取运单入库单信息失败')
      }
    },
    // 跳转海外仓编辑
    async goAbroad(s) {
      const data = await searchOrderByWaybillNo({
        waybillNo: s.row.abroadWaybillNo
      })

      console.log('data :>> ', data)

      if (data.datas.length === 1) {
        const routeUrl = this.$router.resolve({
          path: '/abroadWaybill/abroadWaybillEdit',
          query: { id: compileStr(data.datas[0].id.toString()) }
        })
        // console.log('routeUrl :>> ', routeUrl)

        window.open(routeUrl.href, '_blank')
      }
    },
    // 中转下单
    async transferAboradWaybill(row) {
      this.$confirm(
        row.abroadWaybillNo ? '是否取消中转下单' : '是否中转下单',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          if (row.abroadWaybillNo) {
            cancelTransferAboradWaybill({
              waybillId: row.id
            }).then(res => {
              if (res.code === 200) {
                this.$message.success('取消中转下单成功！')
                this.queryList()
              } else {
                this.$message.error(res.message || '取消中转下单失败！')
              }
            })
          } else {
            transferCreateAboradWaybill({
              waybillId: row.id
            }).then(res => {
              if (res.code === 200) {
                this.$message.success('中转下单成功！')
                this.queryList()
              } else {
                this.$message.error(res.message || '中转下单失败！')
              }
            })
          }
        })
        .catch(() => {
          return
        })
    },

    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        const values = data.map(item => Number(item[column.property]))
        if (
          !values.every(value => isNaN(value)) &&
          [3, 7, 8, 9].includes(index)
        ) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          // sums[index] += ''
        } else {
          sums[index] = ''
        }
      })

      return sums
    },
    async exportExcel() {
      const data = await downLoadWarehouse({
        waybillId: this.showPackagesWaybillId
      })
      console.log('data :>> ', data)
      if (data.errorMesage) {
        this.$message.error(data.errorMesage)
        return
      }
      if (!data.fileName) return
      window.open(globalData.fileUrl + data.fileName)
    }
  }
}
</script>

<style lang="scss" scoped>
.el-col {
  border-radius: 4px;
}
.operation-icon {
  font-size: large;
}
.pan-btn {
  font-size: 12px;
  //  color: #fff;
  width: 100%;
  text-align: center;
  color: #337ab7;
  padding: 14px 0;
  border-radius: 8px;
  border: none;
  outline: none;
  transition: 600ms ease all;
  position: relative;
  display: inline-block;
  cursor: pointer;

  &:hover {
    color: #30b08f;
    //  background: #ccc;

    &:before,
    &:after {
      background: #30b08f;
      width: 100%;
      transition: 600ms ease all;
    }
  }

  &:before,
  &:after {
    content: '';
    position: absolute;
    top: 0;
    right: 0;
    height: 2px;
    width: 0;
    transition: 400ms ease all;
  }

  &::after {
    right: inherit;
    top: inherit;
    left: 0;
    bottom: 0;
  }
}

.btn-active {
  color: #30b08f;
  //  background: #ccc;

  &:before,
  &:after {
    background: #30b08f;
    width: 100%;
    transition: 600ms ease all;
  }
}

.financial-title {
  color: rgba(0, 0, 0, 0.45);
  font-size: 16px;
  text-align: center;
}

.financial-title-money {
  color: #666;
  font-size: 20px;
  text-align: center;
}

.shadow {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.form-inline {
  border-top: 1px solid #ccc;
  .el-form-item--mini.el-form-item,
  .el-form-item--small.el-form-item {
    margin-bottom: 8px;
  }
}
</style>
<style lang="scss">
.table-box th {
  padding: 2px 0;
}
</style>
